package com.papper.common.service.tripartite;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.papper.common.bean.biz.BizDatasourceConfig;
import com.papper.common.bean.biz.BizTemplateConfig;
import com.papper.common.bean.biz.BizTemplateGroup;
import com.papper.common.bean.sys.SysCode;
import com.papper.common.bean.sys.SysConfig;
import com.papper.common.domain.DBColumn;
import com.papper.common.domain.JdbcTypeHelp;
import com.papper.common.domain.TableColumn;
import com.papper.common.service.biz.BizTemplateConfigService;
import com.papper.common.service.sys.SysCodeService;
import com.papper.common.service.sys.SysConfigService;
import com.papper.common.utils.JavaBeansUtil;
import com.papper.common.utils.helper.ThymeleafHelp;
import com.papper.common.utils.tool.DateTool;
import com.papper.common.utils.tool.FileTool;
import com.papper.common.utils.tool.StringTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;

import java.util.List;

/**
 * @author:LaJiao
 * @date 2022年03月25日
 * @time 15时10
 * @Description:
 */
@Service("CodeGenService")
public class CodeGenService {
    private static final Logger logger = LoggerFactory.getLogger(CodeGenService.class);
    @Autowired
    JDBCService              jdbcService;
    @Autowired
    SysCodeService           sysCodeService;
    @Autowired
    SysConfigService         sysConfigService;
    @Autowired
    BizTemplateConfigService bizTemplateConfigService;

    public void codeGen(BizDatasourceConfig datasourceConfig, BizTemplateGroup templateGroup, String outPath, String basePackage, String sysAuthor, String tables, String temps) {
        List<SysCode>           sysCodes           = sysCodeService.findChild("ThymeleafContext");
        List<SysConfig>         DbModels           = sysConfigService.findChild("DbModel");
        List<String>            tableCon           = Splitter.on(',').trimResults().omitEmptyStrings().splitToList(tables);
        List<String>            tempsCon           = Splitter.on(',').trimResults().omitEmptyStrings().splitToList(temps);
        List<BizTemplateConfig> bizTemplateConfigs = bizTemplateConfigService.findByGroup(templateGroup.getId());
        // 获取数据表结构
        List<TableColumn> allTables = jdbcService.mysqlTable(datasourceConfig);
        for (TableColumn tableColumn : allTables) {
            if (!tableCon.contains(tableColumn.getName())) {
                continue;
            }
            Context context = new Context();
            for (SysCode sysCode : sysCodes) {
                context.setVariable(sysCode.getCodeKey(), sysCode.getCodeValue());
            }
            context.setVariable("outPath", outPath);
            String beanModel = "biz";
            String tableName = tableColumn.getName();
            if (DbModels != null && !DbModels.isEmpty()) {
                for (SysConfig dbModel : DbModels) {
                    if (tableName.startsWith(dbModel.getCodeKey())) {
                        beanModel = dbModel.getCodeTags();
                        break;
                    }
                }
            }
            context.setVariable("basePackage", basePackage);
            context.setVariable("beanModel", beanModel);
            context.setVariable("SysAuthor", sysAuthor);
            context.setVariable("nowTime", DateTool.getNowStr());
            context.setVariable("beanDesc", tableColumn.getComment());
            context.setVariable("beanTable", tableName);
            context.setVariable("beanName", JavaBeansUtil.getCamelCaseString(tableName, true));
            context.setVariable("beanNameL", JavaBeansUtil.getCamelCaseString(tableName, false));
            context.setVariable("actionBaseUrl", "/" + tableName.replace("_", "/"));

            List<DBColumn>   columns       = jdbcService.mysql(datasourceConfig, tableColumn.getName());
            List<JSONObject> beanFieldList = Lists.newLinkedList();
            for (DBColumn c : columns) {
                if (c.getName().equals("id")) {
                    c.setType("bigint");
                }
                JSONObject column = new JSONObject();
                column.put("columnDesc", c.getComment());
                column.put("columnEng", c.getName());
                column.put("columnType", JdbcTypeHelp.I().getJavaType(c.getType()));
                column.put("columnJava", JavaBeansUtil.getCamelCaseString(c.getName(), false));
                column.put("columnJavaB", JavaBeansUtil.getCamelCaseString(c.getName(), true));
                column.put("jdbcType", JdbcTypeHelp.I().getJdbcType(c.getType()));
                column.put("columnMax", StringTool.isBlank(c.getLength()) ? "32" : c.getLength());
                beanFieldList.add(column);
            }
            context.setVariable("beanFieldList", beanFieldList);
            // 生成代码
            for (BizTemplateConfig bizTemplateConfig : bizTemplateConfigs) {
                if (!tempsCon.contains(bizTemplateConfig.getName())) {
                    continue;
                }
                String tempCon  = ThymeleafHelp.I().process(bizTemplateConfig.getContent(), context);
                String fileName = ThymeleafHelp.I().process(bizTemplateConfig.getFileName(), context);
                if (!fileName.contains("html")) {
                    tempCon = tempCon.replace("</th:block>", "");
                }
                String filePath = ThymeleafHelp.I().process(bizTemplateConfig.getFolder(), context);

                StringBuffer pathBuffer = new StringBuffer();
                pathBuffer.append(filePath);
                pathBuffer.append("/");
                pathBuffer.append(fileName);
                FileTool.newFile(pathBuffer.toString(), tempCon);

                logger.info("输出文件地址:{}", pathBuffer.toString());
                logger.info("输出文件内容:{}", tempCon);
            }
        }
    }
}
